import 'package:dio/dio.dart';
import 'package:enjoy_plus/models/location_amap_request.dart';
import 'package:enjoy_plus/pages/house/building_list.dart';
import 'package:enjoy_plus/pages/house/components/list_item.dart';
import 'package:enjoy_plus/utils/location_util.dart';
import 'package:enjoy_plus/utils/logger.dart';
import 'package:enjoy_plus/utils/toast.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';

class HouseGetPostion extends StatefulWidget {
  const HouseGetPostion({super.key});

  @override
  State<HouseGetPostion> createState() => _HouseGetPostionState();
}

class _HouseGetPostionState extends State<HouseGetPostion> {
  String address = '获取中...';
  // 附近社区
  List<String> communities = ['搜寻中...'];
  static const amapKey = 'f45cf8c40fbd4a5da5fdc58e4886a5cd';

  // 创建dio实例
  final dio = Dio(BaseOptions(
    connectTimeout: const Duration(seconds: 5),
    receiveTimeout: const Duration(seconds: 5),
  ));

  @override
  void initState() {
    super.initState();
    requestLocationPermission();
  }

  Future<void> requestLocationPermission() async {
    PermissionStatus status = await Permission.location.request();
    if (status.isGranted) {
      // ToastUtil.showSuccess('位置权限授予');
      getLocation();
    } else {
      ToastUtil.showError('位置权限未授予, 请去设置中心开启');
    }
  }

  Future<void> getLocation() async {
    // 先检查权限
    try {
      final canIGetLocation = await LocationUtil.checkLocationPermission();
      if (canIGetLocation) {
        // 获取位置
        // ToastUtil.showSuccess('正在获取位置');
        final position = await LocationUtil.getCurrentLocation();
        if (position != null) {
          // ToastUtil.showSuccess('${position.latitude}, ${position.longitude}');
          // TODO: 处理位置信息
          getAddress(position.latitude, position.longitude);
          searchNearby(position.latitude, position.longitude);
        }
      } else {
        ToastUtil.showError('无法获取位置');
      }
    } catch (e) {
      ToastUtil.showError('获取位置失败:' + e.toString());
    }
  }

  void onRelocatePressed() {
    requestLocationPermission();
  }

  //高德API逆地理编码
  Future<void> getAddress(double latitude, double longitude) async {
    try {
      final res = await dio.get(
        'https://restapi.amap.com/v3/geocode/regeo',
        queryParameters: {
          'key': amapKey,
          'location': '121,31',
        },
      );

      final data = res.data;
      if (data['status'] != '1') {
        throw Exception('获取地址请求失败');
      }

      final address = data['regeocode']?['formatted_address'];
      if (address == null || address.isEmpty) {
        throw Exception('获取地址失败,请检查经纬度坐标');
      }

      setState(() {
        this.address = address;
      });
    } catch (e) {
      logger.e('逆地理编码失败: $e');
      setState(() {
        address = '默认地址';
      });
    }
  }

  //周边位置搜索
  Future<void> searchNearby(double latitude, double longitude) async {
    try {
      final res = await dio.get(
        'https://restapi.amap.com/v5/place/text',
        queryParameters: {
          'key': amapKey,
          'keywords': '中山公寓',
          'types': '120000',
        },
      );

      final data = res.data;
      if (data['status'] != '1') {
        throw Exception('获取周边地址失败');
      }

      final pois = data['pois'] as List?;
      if (pois == null || pois.isEmpty) {
        throw Exception('未找到周边地址');
      }

      setState(() {
        communities =
            pois.map((poi) => '${poi['name']} (${poi['address']})').toList();
      });
      logger.d(communities);
    } catch (e) {
      logger.e('获取周边地址失败: $e');
      setState(() {
        communities = ['暂无数据'];
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('选择社区'),
        backgroundColor: const Color(0xFFF1F2F6),
        centerTitle: true,
        leading: IconButton(
            onPressed: () => Navigator.pop(context),
            icon: const Icon(Icons.arrow_back_ios)),
      ),
      body: Container(
        color: const Color(0xFFF1F2F6),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Padding(
              padding: EdgeInsets.all(12),
              child: Text('当前地址',
                  style: TextStyle(fontSize: 14, color: Colors.grey)),
            ),
            Container(
              padding: const EdgeInsets.only(left: 12, right: 2),
              width: double.infinity,
              color: Colors.white,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Expanded(
                    child: Text(address),
                  ),
                  ElevatedButton(
                    onPressed: onRelocatePressed,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.white,
                      foregroundColor: Colors.blue,
                      elevation: 0,
                      shadowColor: Colors.transparent,
                    ),
                    child: const Row(
                      children: [
                        Icon(Icons.location_searching,
                            size: 14, color: Colors.blue),
                        Text('重新定位', style: TextStyle(color: Colors.blue)),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            const Padding(
              padding: EdgeInsets.all(12),
              child: Text('附近社区',
                  style: TextStyle(fontSize: 14, color: Colors.grey)),
            ),
            Expanded(
              child: ListView.builder(
                shrinkWrap: true,
                itemCount: communities.length,
                itemBuilder: (context, index) {
                  return RoomListItem(
                      room: communities[index],
                      onPressed: () {
                        Navigator.pushNamed(context, '/buildingList',
                            arguments: communities[index]);
                      });
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    // 页面销毁时关闭dio
    dio.close();
    super.dispose();
  }
}
